package com.example.demo.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Description: TODO(解决跨域)
 * @Author da
 * @Date 2021/8/16 下午 7:27
 */
@Configuration
public class CorsConfig
{
    //    当前跨域请求最大有效时长,这里默认是一天
    private static final long MAX_AGE = 24 * 60 * 60;

    public CorsConfiguration buildConfig()
    {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");// 设置访问源地址
        corsConfiguration.addAllowedHeader("*");// 设置访问源请求头
        corsConfiguration.addAllowedMethod("*");// 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);// 当前跨域请求最大有效时长
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());// 对接口配置跨域请求
        return new CorsFilter(source);
    }
}
